package com.topisv.tms.platform.furun;

import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.topisv.tms.entity.Area;
import com.topisv.tms.entity.Customers;
import com.topisv.tms.entity.EdiOrder;
import com.topisv.tms.entity.EdiOrderItem;
import com.topisv.tms.entity.ShopSource;
import com.topisv.tms.entity.log.OrderLog;
import com.topisv.tms.entity.stock.ViewCusStock;
import com.topisv.tms.repository.log.OrderLogDao;
import com.topisv.tms.rest.entity.Batch;
import com.topisv.tms.service.AreaService;
import com.topisv.tms.service.CustomerAreaGroupService;
import com.topisv.tms.service.CustomersService;
import com.topisv.tms.service.EdiOrderService;
import com.topisv.tms.service.ShopSourceService;
import com.topisv.tms.service.log.OrderLogService;
import com.topisv.tms.service.stock.ViewCusStockService;
import com.topisv.tms.service.work.WorkOrderService;
import com.topisv.tms.utils.DateUtils;
import com.topisv.tms.utils.TimeUtil;
import com.topisv.tms.utils.vo.RestAreaGroupVo;
import com.topisv.tms.utils.vo.RestCustomersAreagroupVo;

/**
 * 批次的Restful API的Controller.
 * 
 * @author calvin
 */
@Controller
@RequestMapping(value = "/api/furun")
public class FRRestController {

	@Autowired
	private EdiOrderService ediOrderService;
	
	@Autowired
	private ShopSourceService shopSourceService;
	
	@Autowired
	private CustomersService customerService;
	
	@Autowired
	private AreaService areaService;
	
	@Autowired
	private ViewCusStockService viewCusStockService;
	
	@Autowired
	private CustomerAreaGroupService customerAreaGroupService;
	
	@Autowired
	private WorkOrderService workOrderService;
	
	@Autowired
	private OrderLogService orderLogService;
	
	@Autowired
	private OrderLogDao orderLogDao;
	
	
	private static final Logger logger = LoggerFactory.getLogger(FRRestController.class);
	

	@RequestMapping(value = "synOrder.py",method = RequestMethod.POST)
	public void create(@RequestParam(value = "appkey") String appkey,@RequestParam(value = "appsecret") String appsecret
			,@RequestParam(value = "data") String data,HttpServletRequest request,HttpServletResponse response) {
		
		Map map = new HashMap();
		ObjectMapper objectMapper = new ObjectMapper();
		JSONObject json=null;
		logger.info("富润同步订单jsonData=" + data);
		Customers customers =null;
		String areaGroupCode = "";
		try
		{
			json=JSONObject.fromObject(data);
			
			json = json.getJSONObject("trade");
			EdiOrder ediOrder = new EdiOrder();
			ediOrder.setCustomerCode(appkey);
			ediOrder.setErpType("fr");
			String owner_code = json.getString("owner_code");//客户编码
			areaGroupCode = json.getString("warehouse_code");//仓库编码
			String site_name = json.getString("site_name");//店铺名称
			ShopSource shopSource = null;
			shopSource = shopSourceService.findShopName(site_name);
			if(null != shopSource)
			{
				ediOrder.setCustomerCode(owner_code);
				ediOrder.setShopCode(shopSource.getShopCode());
				ediOrder.setShopna(shopSource.getShopName());
				customers = customerService.findByCustomerCode(owner_code);
				if(null != customers)
				{
					Area area = areaService.findByAreaName2(json.getString("receiver_state")+"%");
					if(null != area)
					{
						ediOrder.setAreaGroupCode(areaGroupCode);
						ediOrder.setProvco(area.getAreaCode());
					}
				}
				else
				{
					map.put("code", "4");
					map.put("message", "找不到客户信息");
				}
				
			}
			else
			{
				map.put("code", "5");
				map.put("message", "找不到店铺");
			}
			
			if("1".equals(json.getString("is_cod")))
			{
				ediOrder.setIsTopay(true);
				if("no".equals(shopSource.getPayAfter()))
				{
					map.put("code", "7");
					map.put("message", "货到付款不处理");
				}
			}
			else if("0".equals(json.getString("is_cod")))
			{
				ediOrder.setIsTopay(false);
			}
			if(null != map.get("code")  && !"".equals(map.get("code")))
			{
				try {
					objectMapper.writeValue(response.getWriter(), map);
				} catch (Exception e1) {
					logger.info("保存失败:" + map.get("code") + "--" + map.get("message"));
				}
				return;
			}
			ediOrder.setShopId(shopSource.getHtShopId());
			//ediOrder.setOrdeno(json.getString("outerCode"));
			ediOrder.setCustomerOrdeno(json.getString("bil_no"));
			ediOrder.setFromno(json.getString("tid"));
			String tms_code=json.getString("tms_code");
			ediOrder.setCacode(tms_code);
			ediOrder.setOldCacode(tms_code);
			ediOrder.setCaname(json.getString("tms_name"));
			ediOrder.setCrtime(new Date());
			ediOrder.setAdtime(TimeUtil.getDateMMSS(json.getString("created")));
			ediOrder.setOrderStatus(json.getString("status"));
			ediOrder.setBunick(json.getString("buyer_nick"));
			ediOrder.setCustna(json.getString("receiver_name"));
			ediOrder.setRecena(json.getString("receiver_name"));
			ediOrder.setPostco(json.getString("receiver_zip"));
			try {
				ediOrder.setTeleph(json.getString("receiver_phone"));
			} catch (Exception e2) {
				// TODO Auto-generated catch block
				ediOrder.setTeleph("");
			}
			try {
				ediOrder.setMobile(json.getString("receiver_mobile"));
			} catch (Exception e2) {
				// TODO Auto-generated catch block
				ediOrder.setMobile("");
			}
			String sellerMemo = json.getString("seller_memo");
			if("HN".equals(sellerMemo) || "HD".equals(sellerMemo) || "HB".equals(sellerMemo))
			{
				areaGroupCode = sellerMemo;
				ediOrder.setAreaGroupCode(sellerMemo);
			}
			else
			{
				ediOrder.setSememo(sellerMemo);
			}
			ediOrder.setProvna(json.getString("receiver_state"));
			ediOrder.setCityna(json.getString("receiver_city"));
			try {
				ediOrder.setDistna(json.getString("receiver_district"));
			} catch (Exception e) {
				// TODO Auto-generated catch block
				ediOrder.setDistna("");
			}
			ediOrder.setAddres(ediOrder.getProvna() + ediOrder.getCityna() + ediOrder.getDistna() + json.getString("receiver_address"));
			//ediOrder.setSememo(json.getString("sellerMemo"));
			//ediOrder.setBumemo(json.getString("buyerMemo"));
			ediOrder.setStatus("pending");
			ediOrder.setActuallyPaid(Double.parseDouble(json.getString("payment")));
			
			List<EdiOrderItem> item = new ArrayList<EdiOrderItem>();
			JSONArray jsonArray = json.getJSONArray("orders");
			int sku_num = 0;
			Map<String,EdiOrderItem> itemMap = new HashMap<String,EdiOrderItem>();
			if(null != jsonArray)
			{
				for(int i=0; i<jsonArray.size(); i++)
				{
					JSONObject jsonObject = (JSONObject)jsonArray.opt(i);
					EdiOrderItem ediOrderItemHT = new EdiOrderItem();
					ediOrderItemHT.setOrdeno(json.getString("bil_no"));
					ediOrderItemHT.setSku(jsonObject.getString("product_no"));
					ediOrderItemHT.setNam(jsonObject.getString("title"));
					ediOrderItemHT.setQty(jsonObject.getInt("num"));
					ediOrderItemHT.setCrtime(new Date());
					ediOrderItemHT.setPri(Double.parseDouble(jsonObject.getString("price")));
					ediOrderItemHT.setPay(Double.parseDouble(jsonObject.getString("total_fee")));
					ediOrderItemHT.setCustomerCode(ediOrder.getCustomerCode());
					EdiOrderItem tmp = itemMap.get(ediOrderItemHT.getSku());
					if(tmp == null)
					{
						if(ediOrderItemHT.getQty() > 0)
						{
							itemMap.put(ediOrderItemHT.getSku(), ediOrderItemHT);
							//item.add(ediOrderItemHT);
							sku_num += jsonObject.getInt("num");
						}
					}
					else
					{
						if(ediOrderItemHT.getQty() > 0)
						{
							tmp.setQty(tmp.getQty()+ediOrderItemHT.getQty());
							sku_num += jsonObject.getInt("num");
						}
					}
					
					
				}
			}
			
			
			for(String key:itemMap.keySet())
			{
				item.add(itemMap.get(key));
			}
			if(sku_num > 1)
			{
				ediOrder.setOrderType("multiple");
			}
			else if(sku_num == 1)
			{
				ediOrder.setOrderType("single");
				
			}
			ediOrder.setOrderStatus("ok");
			map.put("code", "0");
			map.put("message", "接收成功");
			ediOrder.setSkuQty(sku_num);
			ediOrder.setSkulst(item);
			ediOrder.setPatime(new Date());
			String expressCode = ediOrder.getCacode();
			String expressCodes = shopSource.getExpressCodes();
			if(null != expressCodes && !"".equals(expressCodes))
			{
				if(expressCodes.indexOf(expressCode) == -1)
				{
					ediOrder.setOrderStatus("no");
					map.put("code", "8");
					map.put("message", "非合作快递公司订单");
				}
			}
			
			if("single".equals(shopSource.getOrderType()) && sku_num == 1)
			{
				ediOrder.setOrderStatus("no");
				map.put("code", "9");
				map.put("message", "单件订单不处理");
			}
			if("multiple".equals(shopSource.getOrderType()) && sku_num > 1)
			{
				ediOrder.setOrderStatus("no");
				map.put("code", "10");
				map.put("message", "多件订单不处理");
			}
			
			try {
				
				ediOrder=ediOrderService.saveEdiOrderPlat(ediOrder);
				if("cancel".equals(ediOrder.getStatus())||"no".equals(ediOrder.getOrderStatus())||"repeat".equals(ediOrder.getStatus())){
					map.put("code", "201");
					map.put("message", ediOrder.getMessage());
				}
				/*else
				{
					try {
						OrderLog orderLog=new OrderLog(
								ediOrder.getOrdeno(),
								ediOrder.getCustomerCode(),
								"0", //操作类型 （1.创建批次 2.创建任务  3.拣货完成 4.包装完成 5.发货完成 6.签收完成 7.异常登记 8.完成灯光拣选任务 9.打印单据）
								null,
								new Date(),
								null,
								"系统接收订单");
						this.orderLogDao.save(orderLog);
					} catch (Exception e) {
						logger.error("失败:",e);
					}
				}*/
			} catch (Exception e1) {
				// TODO Auto-generated catch block
				map.put("code", "12");
				map.put("message", "保存失败");
				logger.error("保存订单失败", e1);
			}
			
		}
		catch(Exception e)
		{
			map.put("code", "13");
			map.put("message", "接收失败");
			logger.error("json格式错误==" , e);
		}
		try {
			objectMapper.writeValue(response.getWriter(), map);
			logger.info("返回结果:" + map.get("code") + "--" + map.get("message"));
		} catch (Exception e1) {
		}
		
	}
	@RequestMapping(value = "queryStock.py",method = RequestMethod.POST)
	public void queryStock(@RequestParam(value = "appkey") String appkey,@RequestParam(value = "appsecret") String appsecret
			,@RequestParam(value = "data") String data,HttpServletRequest request,HttpServletResponse response) {
		
		Map map = new HashMap();
		Batch batch = null;
		logger.info("富润查询库存jsonData=" + data);
		JSONObject json=null;
		JSONObject jsonRes = null;
		PrintWriter out = null;
		try
		{
			json=JSONObject.fromObject(data);
			jsonRes = new JSONObject();
			out = response.getWriter();
			String owner_code = json.getString("owner_code");
			String warehouse = json.getString("warehouse");
			String sku = json.getString("sku");
			int pageNum = 1;
			int pageSize = 20;
			try {
				String pageNum_str = json.getString("pageNum");
				String pageSize_Str = json.getString("pageSize");
				if(!"".equals(pageNum_str))
				{
					pageNum = Integer.parseInt(pageNum_str);
				}
				if(!"".equals(pageSize_Str))
				{
					pageSize = Integer.parseInt(pageSize_Str);
				}
			} catch (Exception e) {
			}
			if(!"".equals(sku))
			{
				Page<ViewCusStock> page_sku = this.viewCusStockService.loadViewStock(owner_code,warehouse,sku,"sku",pageNum,pageSize);
				if(page_sku.hasContent())
				{
					List<ViewCusStock> content = page_sku.getContent();
					StockVo stockVo = new StockVo();
					for(ViewCusStock viewCusStock : content)
					{
						stockVo.setSku(viewCusStock.getSku());
						stockVo.setNum(viewCusStock.getSalesNum());
					}
					jsonRes.put("code", "0");
					jsonRes.put("message", "success");
					jsonRes.put("num", stockVo.getNum());
				}
				else
				{
					jsonRes.put("code", "1");
					jsonRes.put("message", "无数据");
				}
			}
			else
			{
				Page<ViewCusStock> page_sku = this.viewCusStockService.loadViewStock(owner_code,warehouse,sku,"sku",pageNum,pageSize);
				if(page_sku.hasContent())
				{
					List<ViewCusStock> content = page_sku.getContent();
					long totalNumber = page_sku.getTotalElements();
					int current =  page_sku.getNumber() + 1;
					int totalPage = page_sku.getTotalPages();
					List<StockVo> list = new ArrayList<StockVo>();
					for(ViewCusStock viewCusStock : content)
					{
						StockVo stockVo = new StockVo();
						stockVo.setSku(viewCusStock.getSku());
						stockVo.setNum(viewCusStock.getSalesNum());
						list.add(stockVo);
					}
					jsonRes.put("code", "0");
					jsonRes.put("message", "success");
					jsonRes.put("totalPage", totalPage);
					jsonRes.put("totalNum", totalNumber);
					jsonRes.put("currentPage", current);
					jsonRes.put("data", list);
				}
				else
				{
					jsonRes.put("code", "1");
					jsonRes.put("message", "无数据");
				}
			}
			
			
			try {
				out.print(jsonRes.toString());
				out.close();
			} catch (Exception e1) {
				logger.info("json格式错误");
			}
		}
		catch(Exception e)
		{
			jsonRes.put("code", "1");
			jsonRes.put("message", "error");
			try {
				out.print(jsonRes.toString());
				out.close();
			} catch (Exception e1) {
				logger.info("json格式错误");
			}
			return;
		}
		
	}
	
	@RequestMapping(value = "cancelOrder.py",method = RequestMethod.POST)
	public void cancelOrder(@RequestParam(value = "appkey") String appkey,@RequestParam(value = "appsecret") String appsecret
			,@RequestParam(value = "data") String data,HttpServletRequest request,HttpServletResponse response) {
		
		Map map = new HashMap();
		ObjectMapper objectMapper = new ObjectMapper();
		JSONObject json=null;
		try
		{
			logger.info("富润取消订单jsonData=" + data);
			
			json=JSONObject.fromObject(data);
			
			String order_code = json.getString("order_code");
			EdiOrder ediOrder = ediOrderService.findByOrdernoOrCustomerorderno(order_code);
			workOrderService.cancelOrder(ediOrder.getOrdeno(),"ADMIN");
			map.put("code", "0");
			map.put("message", "success");
			try {
				objectMapper.writeValue(response.getWriter(), map);
			} catch (Exception e1) {
				logger.info("json格式错误");
			}
		}
		catch(Exception e)
		{
			map.put("code", "1");
			map.put("message", "error");
			try {
				objectMapper.writeValue(response.getWriter(), map);
			} catch (Exception e1) {
				logger.info("json格式错误");
			}
			return;
		}
		
	}
	
	@RequestMapping(value = "queryOrderStatus.py",method = RequestMethod.POST)
	public void queryOrderStatus(@RequestParam(value = "appkey") String appkey,@RequestParam(value = "appsecret") String appsecret
			,@RequestParam(value = "data") String data,HttpServletRequest request,HttpServletResponse response) {
		
		JSONObject json=null;
		JSONObject jsonRes = null;
		PrintWriter out = null;
		try
		{
			logger.info("富润查询订单状态jsonData=" + data);
			jsonRes = new JSONObject();
			out = response.getWriter();
			json=JSONObject.fromObject(data);
			String order_code = json.getString("order_code");
			EdiOrder ediOrder = ediOrderService.findByOrdernoOrCustomerorderno(order_code);
			if(null != ediOrder)
			{
				List<StatusVo> svoList = new ArrayList<StatusVo>();
				/*StatusVo svo = new StatusVo();
				svo.setTime(DateUtils.format(ediOrder.getPatime(),"yyyy-MM-dd HH:mm:ss"));
				svo.setContext("已接单");
				svo.setStatus("0");
				svoList.add(svo);*/
				List<OrderLog>  orderLog = orderLogService.loadLogByOrderno(ediOrder.getOrdeno());
				if(null != orderLog && !orderLog.isEmpty())
				{
					for(OrderLog ol : orderLog)
					{
						StatusVo _svo = new StatusVo();
						_svo.setTime(DateUtils.format(ol.getOperateTime(),"yyyy-MM-dd HH:mm:ss"));
						_svo.setContext(ol.getAboutInfo());
						_svo.setStatus(ol.getOperateType());
						svoList.add(_svo);
					}
				}
				jsonRes.put("code", "0");
				jsonRes.put("message", "success");
				jsonRes.put("data", svoList);
			}
			else
			{
				jsonRes.put("code", "2");
				jsonRes.put("message", "订单号不存在");
			}
			try {
				out.print(jsonRes.toString());
				out.close();
			} catch (Exception e1) {
				logger.info("json格式错误");
			}
		}
		catch(Exception e)
		{
			jsonRes.put("code", "1");
			jsonRes.put("message", "error");
			try {
				out.print(jsonRes.toString());
				out.close();
			} catch (Exception e1) {
				logger.info("json格式错误");
			}
			return;
		}
		
	}

}
